package org.janusproject.demos.acl.request.agent;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.janusproject.acl.ACLAgent;
import org.janusproject.acl.protocol.AbstractFipaProtocol;
import org.janusproject.acl.protocol.EnumFipaProtocol;
import org.janusproject.acl.protocol.FipaConversationManager;
import org.janusproject.demos.acl.request.organization.RequestOrganization;
import org.janusproject.demos.acl.request.role.Requester;
import org.janusproject.kernel.address.AgentAddress;
import org.janusproject.kernel.crio.core.GroupAddress;
import org.janusproject.kernel.status.Status;
import org.janusproject.kernel.status.StatusFactory;
import org.janusproject.kernel.util.sizediterator.SizedIterator;

public class ACLProtocolSender extends ACLAgent {

	private static final long serialVersionUID = -7078376398776599011L;

	protected FipaConversationManager protocolManager;

	@Override
	public Status activate(Object... parameters) {
		
		protocolManager = new FipaConversationManager(this);
		AbstractFipaProtocol protocol =  protocolManager.createConversation(EnumFipaProtocol.FIPA_REQUEST, "First request protocol");		
		Logger.getAnonymousLogger().log(Level.INFO, "sender protocol created");
		
		SizedIterator<AgentAddress> agents = getLocalAgents();	
		
		while (agents.hasNext()) 
		{
			AgentAddress participant = agents.next();			
			if ( participant != getAddress() ) 
			{
				protocol.initiate(getAddress(), participant);
			}
		}
		
		GroupAddress groupAddress = getOrCreateGroup(RequestOrganization.class);	
		
		if ( !requestRole( Requester.class, groupAddress, protocol ) ) {
			return StatusFactory.cancel(this);
		}
		
		return StatusFactory.ok(this);
	}
}